package com.cssy.xxkj.basic.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicSubjectsDO;
import com.cssy.xxkj.basic.service.IBasicSubjectsService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
@Controller
@RequestMapping("/basic/subjects")
public class SubjectsController extends BaseController<BasicSubjectsDO>{
	private static final String EIDT = "/xxkj/basic/subjects/SubjectsOperation";//添加、修改、显示页面
	private static final String MANAGER = "/xxkj/basic/subjects/SubjectsManager";
	
	@Resource(name="basicSubjectsService")
	private IBasicSubjectsService basicSubjectsService;
	
	@Resource(name="syCodeService")
	private SyCodeService syCodeService;
	
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		String pid = request.getParameter("pid");
		scs.setRemovedProperty(null);
		hander.getWheres(scs);
		scs.addCondition("zd003CategoryId", pid,SearchCondition.OP_EQUAL);
		SearchResult result=	basicSubjectsService.findListByExample(scs);
		List<BasicSubjectsDO> m = result.getResults();
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}
	
	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			BasicSubjectsDO basicSubjectsDO =basicSubjectsService.findListById(id);
			model.addAttribute("basicSubjects",basicSubjectsDO);
			model.addAttribute("flag", "add");
		}else{
			BasicSubjectsDO basicSubjectsDO =basicSubjectsService.findListById(id);
			if(basicSubjectsDO!=null){
				if(basicSubjectsDO.getZd003CategoryId()!=null&&!"".equals(basicSubjectsDO.getZd003CategoryId())){
					BasicSubjectsDO basicSubjectsDO1 =basicSubjectsService.findListById(basicSubjectsDO.getZd003CategoryId());
					model.addAttribute("basicSubjects",basicSubjectsDO1);
				}
			}
			model.addAttribute("basicSubjectsDO",basicSubjectsDO);
			model.addAttribute("flag", "edit");
		}
		return EIDT;
	}
	
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			BasicSubjectsDO curAP, BindingResult result, Model model)
	{
		
		BodyMsg bodyMap=BodyMsg.getInstance();
		try {
				if(curAP.getId()!=null && !"".equals(curAP.getId())){//修改
		
					basicSubjectsService.update(curAP, SessionUtil.getUser(request));
					bodyMap.isSuccess();
					bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
					bodyMap.configWebId(curAP.getId());
				}else{//新增
				
					curAP.setZd001Code(syCodeService.getCode("SJ","SJ",SyCode.DATE_YY_MM,5));
					try {
						basicSubjectsService.save(curAP, SessionUtil.getUser(request));
					} catch (Exception e) {
						e.printStackTrace();
						bodyMap.isFail();
						bodyMap.configWebInfor("数据有误，请检查后重新输入");
						return bodyMap.modelMap;
					}
					bodyMap.isSuccess();
					bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
				}
		} catch (Exception e) {			
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
		
	}
		

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String isDelete = request.getParameter("isDelete");//标识是否是假删除
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(isDelete==null||"0".equals(isDelete)){
					basicSubjectsService.delete(field, SessionUtil.getUser(request));
				}else{
					basicSubjectsService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String tr=null;
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		SearchResult result=	basicSubjectsService.findListByExample(scs);
		List<BasicSubjectsDO> list =result.getResults();
		if(list!=null&&list.size()>0){
			tr=tree(list,list);
		}
		AjaxUtil.printJSonArr(response, tr);
	}
	
	/**
     * 自调函数 生成tree数据
     **/
	private String  tree(List<BasicSubjectsDO> list,List<BasicSubjectsDO> listvo) throws SyBaseException {
		List<BasicSubjectsDO> list2 = new ArrayList<BasicSubjectsDO>();
		StringBuffer sf = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getZd003CategoryId() == null
					|| "".equals(list.get(i).getZd003CategoryId())) {
				list2.add(list.get(i));
				list.remove(i);
				i--;
			}
		}
		sf.append("[");
		for (int i = 0; i < list2.size(); i++) {
			List<BasicSubjectsDO> list1 = new ArrayList<BasicSubjectsDO>();
			sf.append("{");
			sf.append("\"text\":").append("\"")
					.append(list2.get(i).getZd002Name()).append("\"")
					.append(",").append("\"id\":").append("\"")
					.append(list2.get(i).getId()).append("\"");
			for (int n = 0; n < listvo.size(); n++) {
				if (list2.get(i).getId()
						.equals(listvo.get(n).getZd003CategoryId())) {
					list1.add(list.get(n));
				}
			}
			if (list1 != null && list1.size() > 0) {
				sf.append(",").append("\"children\":");
				sf.append(tree1(list1,list));
			}
			if (i == (list2.size() - 1)) {
				sf.append("}");
			} else {
				sf.append("},");
			}
		}
		sf.append("]");
		return sf.toString();
	}
	
	/**
     * 自调函数 生成tree数据
     **/
	private String  tree1(List<BasicSubjectsDO> list1,List<BasicSubjectsDO> list) throws SyBaseException {
		List<BasicSubjectsDO> list2 =new ArrayList<BasicSubjectsDO>();
		StringBuffer sf =new StringBuffer();
		sf.append("[");
		for(int i=0;i<list1.size();i++){
					sf.append("{");
					sf.append("\"text\":").append("\"").append(list1.get(i).getZd002Name()).append("\"").append(",").append("\"id\":").append("\"").append(list1.get(i).getId()).append("\"");
					for(int n=0;n<list.size();n++){
						if(list1.get(i).getId().equals(list.get(n).getZd003CategoryId())){
							list2.add(list.get(n));
						}
					}
					if(list2!=null&&list2.size()>0){
						sf.append(",").append("\"children\":");
						sf.append(tree1(list2,list));
					}
					if(i==(list1.size()-1)){
						sf.append("}");
					}else{
						sf.append("},");
					}
		}
		sf.append("]");
		return sf.toString();
	}
}
